package com.ojoin.trade.common.utils;

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;


/**
 * @author huanggc
 *
 */
public class CacheUtils {

    private Cache defaultCache;
    public static final String COOKIE = "cookie";
    public static final String SL_CATCHDATA_TASK = "sl_catchdata_task";
    
	private static CacheManager cacheManager = SpringUtils.getBean(CacheManager.class);
    
	private CacheUtils(){
		defaultCache = cacheManager.getCache("defaultCache");
	}
	
	 
	public void setString(String key ,String value){
		 defaultCache.put(key, value);
	}
	
	public void setString(String cacheName,String key ,String value){
		getCache(cacheName).put(key, value);
	}
	
	 
	public String getString(String key){
		ValueWrapper cacheElement = defaultCache.get(key);
		if(null==cacheElement){
			return null;
		}
		return (String)cacheElement.get();
	}
	
	
	public String getString(String cacheName,String key){
		ValueWrapper element = getCache(cacheName).get(key);
		return element==null?null:(String)element.get();
	}
	
	 
	public void delete(String key){
		defaultCache.evict(key);
	}
	
	public void delete(String cacheName,String key){
		getCache(cacheName).evict(key);
	}
	
	/**
	 * 获取缓存
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static Object get(String cacheName, String key) {
		ValueWrapper element = getCache(cacheName).get(key);
		return element==null?null:element.get();
	}

	/**
	 * 写入缓存
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put(String cacheName, String key, Object value) {
		getCache(cacheName).put(key, value);
	}

	/**
	 * 从缓存中移除
	 * @param cacheName
	 * @param key
	 */
	public static void remove(String cacheName, String key) {
		getCache(cacheName).evict(key);
		
	}
	
	/**
	 * 从缓存中移除
	 * @param cacheName
	 * 
	 */
	public static void clear(String cacheName) {
		getCache(cacheName).clear();
		
	}
	 
	private static Cache getCache(String cacheName){
		return cacheManager.getCache(cacheName);
	}
	
	public static CacheUtils getInstance(){
		return CacheFacadeHolder.instance;
	}
	
	public static class CacheFacadeHolder{
		private static CacheUtils instance=new CacheUtils();
	}
	
}
